package com.nancy.java_design.singleton;


import com.nancy.java_design.singleton.demo6.Singleton;

import java.io.*;
import java.lang.reflect.Constructor;

public class Client {
    public static void main(String[] args) throws Exception {
        //1.获取Singleton字节码对象
        Class<?> clazz = Singleton.class;
        //2.获取无参构造器
        Constructor obj = clazz.getDeclaredConstructor();
        //3.取消访问检查
        obj.setAccessible(true);
        //4.通过反射调用无参构造器创建对象
        Singleton singleton1 = (Singleton)obj.newInstance();
        Singleton singleton2 = (Singleton)obj.newInstance();
        System.out.println(singleton1 == singleton2);

//        writeObjectFile();
//        readObjectFile();
//        readObjectFile();
    }

    // 序列化破坏单例模式
    public static void writeObjectFile() throws Exception {
        //1.获取单例对象
        Singleton instance = Singleton.getInstance();
        System.out.println(instance);
        //2.序列化到文件中
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\file.txt"));
        oos.close();
    }

    public static void readObjectFile() throws Exception, EOFException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\file.txt"));
        Singleton instance = (Singleton) ois.readObject();
        System.out.println(instance);
        ois.close();
    }
}
